/**
 * 用户信息窗口
 */
var PlayerInfoInGameWindow = Window.extend({
    _ccsFileName: chat.res.PlayerInfoInGameWindow_json,
    _blockLayerOpacity: 0,
    _cdbarArray: null,
    _timeStamp: 5,
    onExit: function () {
        this._cdbarArray = null;
        this.unscheduleAllCallbacks();
        this._super();
    },
    /**
     * 初始化
     * @param playerInfo
     * @param room
     */
    initWindow: function (playerInfo, room, isGid) {
        this._playerInfo = playerInfo;
        this._room = room;
        this._isGid = isGid;
        this._timeStamp = chat.collectFeesEmojiTest ? 5 : 5,
            this._cdbarArray = [];
        this._initPlayerInfoOtherWindow();
        this.onTimer();
        this.scheduleTimer = this.scheduleOnce(this.onTimer, 0.01, "");
    },
    _addDianNode: function (countPag, targetUid, myId) {
        var self = this;
        var interval = 30;
        var _pageNode = self._nodeList["_pageNode"];
        var _dianbg = self._nodeList['_dianbg'];
        var isSelf = targetUid == myId;
        var key = isSelf ? 'self' : 'other';
        var curPageIndex = parseInt(cc.sys.localStorage.getItem("curPageIndex" + key)) || 0;
        _dianbg.setVisible(false);
        var startPos = -(countPag / 2 - 0.5) * interval;
        for (var i = 0; i < countPag; i++) {
            var dianNode = duplicateNode(_dianbg);
            dianNode.setName("dian" + i);
            dianNode.setPositionX(startPos + i * interval);
            dianNode.setVisible(countPag != 1);
            self._nodeList["_pageNode"].addChild(dianNode);
        }
        self._nodeList["_btn_zuo"].setVisible(curPageIndex != 0);
        self._nodeList["_btn_you"].setVisible(curPageIndex != countPag-1);
        var duration = 0.8;
        self._nodeList["_btn_zuo"].runAction(cc.sequence(
                cc.spawn(cc.moveBy(duration, +16, 0), cc.fadeTo(duration, 255))
            , cc.spawn(cc.moveBy(duration, -16, 0), cc.fadeTo(duration, 168))).repeatForever());
        self._nodeList["_btn_you"].runAction(cc.sequence(
                cc.spawn(cc.moveBy(duration, -16, 0), cc.fadeTo(duration, 255))
                , cc.spawn(cc.moveBy(duration, +16, 0), cc.fadeTo(duration, 168))).repeatForever());
        TouchUtil.setOnclickListener(self._nodeList["_touch2"], function (node) {

        });
        TouchUtil.setOnclickListener(self._nodeList["_touch1"], function (node) {

        });
        TouchUtil.setOnclickListener(self._nodeList["_btn_zuo"], function (node) {
            var pageIndex = parseInt(self._nodeList["_PageView"].getCurPageIndex());
            if (pageIndex > 0) {
                self._nodeList["_PageView"].scrollToPage(pageIndex - 1);
            }
        });
        TouchUtil.setOnclickListener(self._nodeList["_btn_you"], function (node) {
            var pageIndex = parseInt(self._nodeList["_PageView"].getCurPageIndex());
            if (pageIndex < countPag - 1) {
                // cc.log(pageIndex + 1);
                self._nodeList["_PageView"].scrollToPage(pageIndex + 1);
            }
        });
        var PageView = self._nodeList["_PageView"];
        PageView.addEventListener(function (sender, type) {
            switch (type) {
                case ccui.PageView.EVENT_TURNING:
                    var pageView = sender;
                    var pageIndex = parseInt(pageView.getCurPageIndex());
                    cc.sys.localStorage.setItem("curPageIndex" + key, pageIndex);
                    self._nodeList["_pageNode"].getChildren();
                    var children = self._nodeList["_pageNode"].getChildren();
                    for (var i = 0; i < children.length; i++) {
                        var child = children[i];
                        child['dian'].setVisible(child.getName() == "dian" + pageIndex);
                    }
                    self._nodeList["_btn_zuo"].setVisible(pageIndex != 0);
                    self._nodeList["_btn_you"].setVisible(pageIndex != countPag-1);
                    break;
                default:
                    break;
            }
        });
        PageView.scrollToPage(curPageIndex);

    },
    /**
     * 初始化界面
     * @private
     */
    _initPlayerInfoOtherWindow: function () {
        var self = this;
        var uid = this._playerInfo['ID'] || this._playerInfo.uid;
        var myId = gameData.uid;
        var targetUid = uid;
        var targetSex = this._playerInfo['Sex'] || this._playerInfo['sex'];
        var targetNickName = this._playerInfo['nickname'] || this._playerInfo['NickName'];
        var targetHeadimgUrl = this._playerInfo['headimgurl'] || this._playerInfo['HeadIMGURL'];
        var targetIP = this._playerInfo['IP'] || this._playerInfo['ip'];
        var targetLocCN = this._playerInfo["locationInfo"] || this._playerInfo['locCN'] || (this._playerInfo['locationCN'] && decodeURIComponent(this._playerInfo['locationCN']));
        if (!targetLocCN || targetLocCN == '') {
            targetLocCN = '未知地址';
        }
        var head = self._nodeList['_head'];
        var lbNickname = self._nodeList['_lb_nickname'];
        var lbId = self._nodeList['_lb_id'];
        var lbIp = self._nodeList['_lb_ip'];
        var male = self._nodeList['_male'];
        var female = self._nodeList['_female'];
        var lbAD = self._nodeList['_lb_ad'];
        var dingwei = self._nodeList['_dingwei'];
        var ip = self._nodeList['_ip'];

        lbAD.setVisible(true);
        lbNickname.setString(ellipsisStr(decodeURIComponent(targetNickName), 7));
        loadImageToSprite(targetHeadimgUrl, head, true);
        lbId.setString(uid);
        lbIp.setString(targetIP);
        lbAD.setString(targetLocCN);
        male.setVisible(targetSex == '1');
        female.setVisible(targetSex == '2');
        self._nodeList["_timer"].setVisible(false);
        self._nodeList["_self"].setVisible(targetUid == myId);
        self._nodeList["_other"].setVisible(targetUid != myId);

        self._nodeList["_gid"].setVisible(false);
        self._nodeList["_lb_gid"].setVisible(false);
        self._nodeList["_lb_gid"].setString('');
        dingwei && dingwei.setVisible(!this._playerInfo.isBiSai);
        ip && ip.setVisible(!this._playerInfo.isBiSai);
        lbIp.setVisible(!this._playerInfo.isBiSai);
        lbAD.setVisible(!this._playerInfo.isBiSai);

        if (targetUid == myId) {
            var emojiNode = self._nodeList["_self"];
            var children = emojiNode.getChildren();
            for (var i = 0; i < children.length; i++) {
                var child = children[i];
                child.setVisible(false);
            }
            if (gameData.ShowEmoji && !chat.collectFeesEmojiTest) {
                EmojiUtil._openSelf = gameData.ShowEmoji;
            }
            var countPag = parseInt((EmojiUtil._openSelf.length - 1) / 10) + 1;
            for (var p = 1; p < countPag; p++) {
                self._nodeList["_PageView"].addPage(duplicateNode(self._nodeList["_Panel"]));
            }
            self._addDianNode(countPag, targetUid, myId);

            for (var i = 0; i < EmojiUtil._openSelf.length; i++) {
                (function (j) {
                    var date = EmojiUtil._emojiCfgSelfIndexs[EmojiUtil._openSelf[j]];
                    var k = date.index;
                    var emojiName = EmojiUtil.effectEmojiCfgSelf[k].name;
                    // cc.log(emojiName);
                    var pageIndex = parseInt(j / 10);
                    var Page = self._nodeList["_PageView"].getPage(pageIndex);
                    var posIndex = j % 10 + 1;
                    var target = self._getEmojiNode(emojiName, posIndex, Page);

                    TouchUtil.setOnclickListener(target, function () {
                        if (target["cdbar"]) {
                            if (getCurTimestamp() - gameData.timestamp > self._timeStamp) {
                                if (gameData.price && gameData.emoji) {
                                    if (target.isXianMian || (!target.isXianMian && target._num > 0)) {
                                        gameData.timestamp = getCurTimestamp();
                                        var msg = JSON.stringify({
                                            roomid: gameData.roomId,
                                            type: 'emoji',
                                            voice: '',
                                            content: date.name,
                                            from: targetUid
                                        });
                                        network.sendEmoji(MsgCode.Query_Emoji, {
                                            cmd: 'useEmoji',
                                            emoji_name: EmojiUtil.effectEmojiCfgSelf[k].name,
                                            emoji_idx: date.name,
                                            coder: MsgCode.ShowChat,
                                            uid: gameData.uid,
                                            room_id: gameData.roomId,
                                            type: 'emoji',
                                            content: date.name
                                        }, "Say/" + msg);
                                        self.removeFromParent(true);
                                    } else {
                                        var buydesc = EmojiUtil.buyTypeDesc[EmojiUtil.buyType];
                                        var str = "是否花1" + buydesc + "\n购买" + gameData.price[EmojiUtil.effectEmojiCfgSelf[k].name] + '次表情使用次数？';
                                        showWindow('BuyEmojiWindow', str, function () {
                                            gameData.timestamp = getCurTimestamp();
                                            var msg = JSON.stringify({
                                                roomid: gameData.roomId,
                                                type: 'emoji',
                                                voice: '',
                                                content: date.name,
                                                from: targetUid
                                            });
                                            network.sendEmoji(MsgCode.Query_Emoji, {
                                                cmd: 'buyAndUse',
                                                count: 1,
                                                emoji_name: EmojiUtil.effectEmojiCfgSelf[k].name,
                                                emoji_idx: date.name,
                                                coder: MsgCode.ShowChat,
                                                uid: gameData.uid,
                                                room_id: gameData.roomId,
                                                type: 'emoji',
                                                currency:EmojiUtil.buyType,
                                                content: date.name
                                            }, "Say/" + msg);
                                            self.removeFromParent(true);
                                        })
                                    }
                                } else {
                                    gameData.timestamp = getCurTimestamp();
                                    self.onSendExpression(date.name, targetUid);
                                }

                            } else {
                                showAlert('表情冷却中，请稍等');
                            }
                        } else {
                            self.onSendExpression(date.name, targetUid);
                        }
                    });
                })(i);
            }
        } else {
            var emojiNode = self._nodeList["_other"];
            if (gameData.ShowItem && !chat.collectFeesEmojiTest) {
                EmojiUtil._openOther = gameData.ShowItem;
            }
            var children = emojiNode.getChildren();
            for (var i = 0; i < children.length; i++) {
                var child = children[i];
                child.setVisible(false);
            }

            var countPag = parseInt((EmojiUtil._openOther.length - 1) / 10) + 1;
            for (var p = 1; p < countPag; p++) {
                self._nodeList["_PageView"].addPage(duplicateNode(self._nodeList["_Panel"]));
            }
            self._addDianNode(countPag, targetUid, myId);

            for (var i = 0; i < EmojiUtil._openOther.length; i++) {
                (function (j) {
                    var date = EmojiUtil._emojiCfgOtherIndexs[EmojiUtil._openOther[j]];
                    var k = date.index;
                    var emojiName = EmojiUtil._effectEmojiCfg[k].name;
                    var pageIndex = parseInt(j / 10);
                    var Page = self._nodeList["_PageView"].getPage(pageIndex);
                    var posIndex = j % 10 + 1;
                    var target = self._getEmojiNode(emojiName, posIndex, Page);
                    TouchUtil.setOnclickListener(target, function () {
                        if (target["cdbar"]) {
                            if (getCurTimestamp() - gameData.timestamp > self._timeStamp) {
                                if (gameData.price && gameData.emoji) {
                                    var _obj = [];
                                    _obj.push(self._playerInfo.uid);
                                    //字牌兼容
                                    var msg = JSON.stringify({
                                        roomid: gameData.roomId,
                                        type: 'biaoqingdonghua',
                                        content: JSON.stringify({
                                            from_uid: gameData.uid,
                                            emoji_idx: k,
                                            emoji_times: 1,
                                            target_uid: _obj
                                        }),
                                        from: gameData.uid
                                    });
                                    if (target.isXianMian || (!target.isXianMian && target._num > 0)) {
                                        gameData.timestamp = getCurTimestamp();
                                        network.sendEmoji(MsgCode.Query_Emoji, {
                                            cmd: 'useEmoji',
                                            emoji_name: EmojiUtil._effectEmojiCfg[k].name,
                                            emoji_idx: k,
                                            uid: gameData.uid,
                                            room_id: gameData.roomId,
                                            emoji_times: 1,
                                            target_uid: _obj
                                        }, "Say/" + msg);
                                        self.removeFromParent(true);
                                    } else {
                                        var buydesc = EmojiUtil.buyTypeDesc[EmojiUtil.buyType];
                                        var str = "是否花1" + buydesc + "\n购买" + gameData.price[EmojiUtil._effectEmojiCfg[k].name] + '次道具使用次数？';
                                        var callBack = function () {
                                            gameData.timestamp = getCurTimestamp();
                                            network.sendEmoji(MsgCode.Query_Emoji, {
                                                cmd: 'buyAndUse',
                                                count: 1,
                                                emoji_name: EmojiUtil._effectEmojiCfg[k].name,
                                                emoji_idx: k,
                                                uid: gameData.uid,
                                                room_id: gameData.roomId,
                                                emoji_times: 1,
                                                currency:EmojiUtil.buyType,
                                                target_uid: _obj
                                            }, "Say/" + msg);
                                            self.removeFromParent(true);
                                        };
                                        showWindow('BuyEmojiWindow', str, callBack);
                                    }
                                } else {
                                    gameData.timestamp = getCurTimestamp();
                                    self.onSendEffectEmoji(k, 1, targetUid);
                                }
                            } else {
                                showAlert('表情冷却中，请稍等');
                            }
                        } else {
                            self.onSendEffectEmoji(k, 1, targetUid);
                        }
                    });
                })(i);
            }
        }
    },
    //添加定时
    _addCDbar: function (target) {
        var self = this;
        if (!target["cdbar"]) {
            var zhezhao = duplicateNode(self._nodeList["_timer"]);
            zhezhao.setVisible(true);
            var cdbar = new cc.ProgressTimer(zhezhao);
            cdbar.setPosition(cc.p(target.getContentSize().width / 2, target.getContentSize().height / 2 + 2));
            cdbar.setType(cc.ProgressTimer.TYPE_RADIAL);
            cdbar.setMidpoint(cc.p(0.5, 0.5));
            cdbar.setOpacity(200);
            cdbar.setReverseDirection(true);
            self._cdbarArray.push(cdbar);
            target.addChild(cdbar);
            target["cdbar"] = cdbar;
        }
    },
    _getEmojiNode: function (emojiName, posIndex, Page) {
        var self = this;
        cc.log(emojiName);
        var emojiNode = duplicateNode(self._nodeList["_emojiNode"]);
        cc.log(chat.res['icon_' + emojiName]);
        emojiNode['emoji'].addChild(new cc.Sprite(chat.res['icon_' + emojiName]));
        Page.addChild(emojiNode);
        emojiNode.setVisible(true);
        Page["emoji" + posIndex].setVisible(true)
        emojiNode.setPosition(Page["emoji" + posIndex].getPosition());
        self._addCDbar(emojiNode);
        self._addNum(emojiNode, emojiName);
        return emojiNode;
    },
    /**
     * 自己给自己发送表情
     * @private
     */
    _meSendMeEmoji: function (date, k, targetUid) {

    },

    //表情
    onSendExpression: function (expression, targetUid) {
        var self = this;
        if (self._playerInfo.UserID || self._playerInfo.ID) {
            var msg = JSON.stringify({
                roomid: gameData.roomId,
                type: 'emoji',
                voice: '',
                content: expression,
                from: targetUid
            });
            network.wsData("Say/" + msg);
        } else {
            network.send(MsgCode.ShowChat, {
                room_id: gameData.roomId,
                type: 'emoji',
                content: expression
            });
        }
        self.removeFromParent(true);
    },
    //道具
    onSendEffectEmoji: function (emojiIdx, times, targetUid) {
        var self = this;
        var _obj = [];
        _obj.push(self._playerInfo.uid);
        if (self._playerInfo.UserID || self._playerInfo.ID) {
            var msg = JSON.stringify({
                roomid: gameData.roomId, type: 'biaoqingdonghua',
                content: JSON.stringify({
                    from_uid: gameData.uid,
                    emoji_idx: emojiIdx,
                    emoji_times: times,
                    target_uid: _obj,
                }), from: gameData.uid
            });
            network.wsData("Say/" + msg);
        } else {
            network.send(4990, {
                room_id: gameData.roomId,
                emoji_idx: emojiIdx,
                emoji_times: times,
                target_uid: _obj,
            });
        }
        self.removeFromParent(true);
    },
    onTimer: function () {
        var self = this;
        var currtime_second = getCurTimestamp();
        if (gameData.timestamp == 0) {
            self.unschedule(self.scheduleTimer);
            return;
        }
        var currtime_tamp = currtime_second - gameData.timestamp;
        if (currtime_tamp < self._timeStamp) {
            var percen = 100 - currtime_tamp / self._timeStamp * 100;
            for (var i = 0; i < 30; i++) {
                var target = self._cdbarArray[i];
                if (target) {
                    target.setPercentage(percen);
                    target.runAction(
                        cc.sequence(
                            cc.progressTo(self._timeStamp - currtime_tamp, 0),
                            cc.callFunc(function () {
                                gameData.timestamp = 0;
                                this.setVisible(false);
                            }, target))
                    );
                }
            }
        }
    },

    _addNum: function (target, name) {
        //临时屏蔽表情收费
        target['xianmian'].setVisible(false);
        target['num'].setVisible(false);
        return;
        target.isXianMian = true;
        target._num = 1;
        if (!gameData.price && !gameData.emoji) {
            if (target['xianmian']) {
                target['xianmian'].setVisible(true);
            }
            if (target['num']) {
                target['num'].setVisible(false);
            }
            return;
        }
        if (gameData.price && !gameData.price[name]) {
            if (target['xianmian']) {
                target['xianmian'].setVisible(false);
            }
            if (target['num']) {
                target['num'].setVisible(false);
            }
        } else if (gameData.price && gameData.price[name] < 0) {//限免
            if (target['xianmian']) {
                target['xianmian'].setVisible(true);
            }
            if (target['num']) {
                target['num'].setVisible(false);
            }
        } else {
            target.isXianMian = false;
            target._num = gameData.emoji[name] || '0';
            if (target['xianmian']) {
                target['xianmian'].setVisible(false);
            }
            if (target['num']) {
                target['num'].setVisible(true);
                target['num'].setString(target._num);
            }
        }
    },
});